package com.qdlc.p2p.biz.service.activity.programme;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.qdlc.p2p.biz.service.activity.AbstractActivityProgrammeHandler;
import com.qdlc.p2p.biz.service.activity.ActivityPlanException;
import com.qdlc.p2p.biz.service.activity.ActivityProgrammeEnum;
import com.qdlc.p2p.biz.service.activity.ActivityProgrammeParam;
import com.qdlc.p2p.biz.service.activity.param.ActivityProgrammeUserCommodityParam;
import com.qdlc.p2p.biz.service.impl.GiveUserExperienceServiceImpl;
import com.qdlc.p2p.common.exception.UserException;
import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.dal.dao.ExperienceDao;
import com.qdlc.p2p.dal.dao.ExperienceRuleDao;
import com.qdlc.p2p.dal.dao.NewActivityAwardLogDao;
import com.qdlc.p2p.dal.dto.Experience;
import com.qdlc.p2p.dal.dto.ExperienceRule;
import com.qdlc.p2p.dal.dto.NewActivityAwardLog;
import com.qdlc.p2p.dal.model.ExperienceModel;

/**
 * 活动:用户体验券
 * @author linya
 */
@Service
public class ActivityProgrammeUserExperienceHandler extends AbstractActivityProgrammeHandler<ActivityProgrammeParam>{

    private static final Logger logger = Logger.getLogger(GiveUserExperienceServiceImpl.class);
    
    @Resource
    private ExperienceDao experienceDao;
    
    @Resource
    private ExperienceRuleDao experienceRuleDao;
    
    @Resource
    private NewActivityAwardLogDao newActivityAwardLogDao;
	
	@Override
	public ActivityProgrammeEnum supportsProgramme() {
		return ActivityProgrammeEnum.EXPERIENCE;
	}

	@Override
	public ActivityProgrammeParam createProgrammeParam(Object attatchmentObject) {
		return new ActivityProgrammeUserCommodityParam();
	}

	@Override
	protected void handleInternal(ActivityProgrammeParam param) {
        
		//获取体验券活动方案,并检测活动规则
		ExperienceRule experienceRule = experienceRuleDao.find(param.getRuleId());
        boolean checkResult = checkExperience(experienceRule);
        if (!checkResult) {
            return;
        }

        handle(experienceRule, param);
	}

	private boolean checkExperience(ExperienceRule experienceRule){
		
		if(experienceRule == null){
			logger.error("++++ 体验券规则不存在,体验券发放失败!");
			return false;
		}
		
		if(experienceRule.getStatus()==0){
			logger.error("++++ 体验券规则未启用,体验券发放失败! id:" + experienceRule.getId());
			return false;
		}
		
		if(experienceRule.getQuotaYes()+1 > experienceRule.getQuota()){
			logger.error("体验券名额已使用完,体验券发放失败! id:" + experienceRule.getId());
			return false;
		}
		
		return true;
	}
	
	@Override
	public void handleCustom(ActivityProgrammeParam param) throws ActivityPlanException {
		Object attatchment = param.getAttatchmentObject();
		if(attatchment == null){
			return;
		}
		if(!(attatchment instanceof ExperienceRule)){
			throw new ActivityPlanException("++++ please set a ExperienceRule to attachmentObject for ActivityProgrammeUpRateParam");
		}
		ExperienceRule experienceRule = (ExperienceRule)attatchment;
		handle(experienceRule, param);
	}

	private void handle(ExperienceRule experienceRule, ActivityProgrammeParam param){

        Experience experience = new Experience();
        experience.setUserId(param.getUser().getUserId());
        experience.setExperienceRuleId(experienceRule.getId());
        experience.setName(experienceRule.getName());
        experience.setAmount(experienceRule.getAmount());
        experience.setValidTime(experienceRule.getValidTime());
        experience.setStatus(ExperienceModel.EXPERIENCE_STATUS_UNUSED);
        experience.setSourceType(param.getActivityPlan().getCnTache());
        experience.setAddTime(DateUtil.getNow());
        experience.setExpiredTime(DateUtil.rollDayStart(experience.getAddTime(), experienceRule.getValidTime()));
        //保存体验券
        save(experience);
        //赠与活动记录
        NewActivityAwardLog newActivityAwardLog = new NewActivityAwardLog();
        newActivityAwardLog.setUser(param.getUser());
        newActivityAwardLog.setTache(param.getActivityPlan().getEnTache());
        newActivityAwardLog.setRuleType(param.getRuleType());
        newActivityAwardLog.setRuleId(param.getRuleId());
        newActivityAwardLog.setCount(1);
        newActivityAwardLog.setAddTime(DateUtil.getNow());
        newActivityAwardLogDao.save(newActivityAwardLog);		
	}
	
	private void save(Experience experience){

        // 更新体验券规则里的已发放名额
        int result = experienceRuleDao.updateQuotaYes(experience.getExperienceRuleId());
        if (result != 1) {
            logger.error("更新体验券已发放名额失败！名额已使用完，体验券发放失败!");
            throw new UserException("名额已使用完，体验券发放失败!");
        }
        
        // 保存体验券
        experienceDao.save(experience);
    }
	
}
